package com.iscreen.dbupgrade.queries;

import java.util.ArrayList;
import java.util.List;

import com.iscreen.dbupgrade.objects.CreateTable;
import com.iscreen.dbupgrade.objects.NewField;
import com.iscreen.dbupgrade.objects.Partitions;
import com.iscreen.dbupgrade.objects.RangePartition;
import com.iscreen.dbupgrade.queries.constants.DBConstants;
import com.iscreen.dbupgrade.queries.objects.PartitionType;
import com.iscreen.dbupgrade.queries.objects.PrimaryKey;

public abstract class CreateTableQuery implements UpgradeQuery
{
	private CreateTable query;
	private PrimaryKey primaryKey = null;
	private PartitionType partitionType = null;

	protected CreateTableQuery(CreateTable query)
	{
		this.query = query;
		createPrimaryKey();
		setPartitions();
	}

	public String getTableName()
	{
		return query.getTableName();
	}
	
	protected String getDescription()
	{
		return query.getDescription();
	}
	
	protected List<NewField> getFields()
	{
		return query.getFields().getField();
	}

	protected Partitions getPartitions()
	{
		return query.getPartitions();
	}
	
	protected PrimaryKey getPrimaryKey()
	{
		return primaryKey;
	}
	
	private void setPartitions()
	{
		if (getPartitions() != null)
		{
			if (getPartitions().getRangePartitions() != null)
			{
				partitionType =  PartitionType.RANGE;
				for (RangePartition partition : getPartitions().getRangePartitions().getRangePartition())
				{
					partition.setName(DBConstants.PREFIX_PARTITION_NAME + partition.getMaxValue());
				}
			}
			else if (getPartitions().getHashPartitions() != null)
			{
				partitionType =  PartitionType.HASH;
			}
		}
	}
	
	protected PartitionType getPartitionType()
	{
		return partitionType;
	}
	
	protected void createPrimaryKey()
	{
		String pkName = DBConstants.PREFIX_PRIMARY_KEY + query.getTableName();
		List<String> pkFields = new ArrayList<String>();
		for (NewField field : getFields())
		{
			if (field.isPk())
			{
				pkFields.add(field.getName());
			}
		}
		if (pkFields.size() > 0)
		{
			primaryKey = new PrimaryKey(pkName, pkFields);
		}
	}
}
